package org.goodsmanager.service.impl;

import org.goodsmanager.entity.Address;
import org.goodsmanager.mapper.AddressMapper;
import org.goodsmanager.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 地址服务实现类
 */
@Service
public class AddressServiceImpl implements AddressService {
    
    @Autowired
    private AddressMapper addressMapper;
    
    @Override
    public Address getAddressById(Long id) {
        return addressMapper.findById(id);
    }
    
    @Override
    public List<Address> getAddressesByUserId(Long userId) {
        return addressMapper.findByUserId(userId);
    }
    
    @Override
    public boolean addAddress(Address address) {
        // 如果设置为默认地址，先取消其他默认地址
        if (address.getIsDefault()) {
            addressMapper.cancelDefaultAddress(address.getUserId());
        }
        
        return addressMapper.insert(address) > 0;
    }
    
    @Override
    public boolean updateAddress(Address address) {
        // 如果设置为默认地址，先取消其他默认地址
        if (address.getIsDefault()) {
            addressMapper.cancelDefaultAddress(address.getUserId());
        }
        
        return addressMapper.update(address) > 0;
    }
    
    @Override
    public boolean deleteAddress(Long id) {
        return addressMapper.deleteById(id) > 0;
    }
    
    @Override
    public boolean setDefaultAddress(Long userId, Long addressId) {
        // 先取消所有默认地址
        addressMapper.cancelDefaultAddress(userId);
        
        // 设置新的默认地址
        return addressMapper.setDefaultAddress(addressId) > 0;
    }
    
    @Override
    public Address getDefaultAddress(Long userId) {
        return addressMapper.findDefaultByUserId(userId);
    }
}